package com.campus.campusdelivery.service.impl;

import com.campus.campusdelivery.constant.MerchantStatus;
import com.campus.campusdelivery.dto.MerchantDto;
import com.campus.campusdelivery.dto.MerchantUpdateRequest;
import com.campus.campusdelivery.entity.Merchant;
import com.campus.campusdelivery.entity.User;
import com.campus.campusdelivery.repository.MerchantRepository;
import com.campus.campusdelivery.repository.UserRepository;
import com.campus.campusdelivery.service.MerchantService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MerchantServiceImpl implements MerchantService {
    
    private final MerchantRepository merchantRepository;
    private final UserRepository userRepository;
    
    @Override
    public MerchantDto getMerchantById(Long id) {
        Merchant merchant = merchantRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        return convertToDto(merchant);
    }
    
    @Override
    public MerchantDto getMerchantByUserId(Long userId) {
        Merchant merchant = merchantRepository.findByUserId(userId)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        return convertToDto(merchant);
    }
    
    @Override
    public Page<MerchantDto> getAllMerchants(String name, Long categoryId, Pageable pageable) {
        if (name != null && !name.trim().isEmpty()) {
            return merchantRepository.findByKeyword(name.trim(), pageable).map(this::convertToDto);
        }
        // 如果只有分类ID，可以扩展查询逻辑
        return merchantRepository.findAll(pageable).map(this::convertToDto);
    }
    
    @Override
    public Page<MerchantDto> getMerchantsByStatus(MerchantStatus status, Pageable pageable) {
        return merchantRepository.findByStatus(status, pageable).map(this::convertToDto);
    }
    
    @Override
    public List<MerchantDto> getOpenMerchants() {
        return merchantRepository.findByIsOpen(true).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public MerchantDto updateMerchant(Long userId, MerchantUpdateRequest request) {
        Merchant merchant = merchantRepository.findByUserId(userId)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        merchant.setShopName(request.getShopName());
        merchant.setDescription(request.getDescription());
        merchant.setLogo(request.getLogo());
        merchant.setAddress(request.getAddress());
        merchant.setPhone(request.getPhone());
        merchant.setBusinessLicense(request.getBusinessLicense());
        
        merchant = merchantRepository.save(merchant);
        return convertToDto(merchant);
    }
    
    @Override
    @Transactional
    public void updateMerchantStatus(Long id, MerchantStatus status, String rejectReason) {
        Merchant merchant = merchantRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        merchant.setStatus(status);
        if (status == MerchantStatus.REJECTED) {
            merchant.setRejectReason(rejectReason);
        }
        
        merchantRepository.save(merchant);
    }
    
    @Override
    @Transactional
    public void toggleMerchantOpenStatus(Long userId) {
        Merchant merchant = merchantRepository.findByUserId(userId)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        if (merchant.getStatus() != MerchantStatus.APPROVED) {
            throw new RuntimeException("商家未通过审核，无法修改营业状态");
        }
        
        merchant.setIsOpen(!merchant.getIsOpen());
        if (merchant.getIsOpen()) {
            merchant.setOpenTime(LocalDateTime.now());
        } else {
            merchant.setCloseTime(LocalDateTime.now());
        }
        
        merchantRepository.save(merchant);
    }
    
    @Override
    @Transactional
    public void deleteMerchant(Long id) {
        Merchant merchant = merchantRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        // 删除商家时，同时禁用用户账户
        User user = merchant.getUser();
        user.setEnabled(false);
        userRepository.save(user);
        
        merchantRepository.delete(merchant);
    }
    
    private MerchantDto convertToDto(Merchant merchant) {
        MerchantDto dto = new MerchantDto();
        BeanUtils.copyProperties(merchant, dto);
        
        // 设置用户信息
        User user = merchant.getUser();
        dto.setUserId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setRealName(user.getRealName());
        dto.setUserPhone(user.getPhone());
        dto.setEmail(user.getEmail());
        
        return dto;
    }
}
